import {Request} from "../../utils/request";
import host from "../../utils/host";
import func from "../../utils/functions";
const Func = new func();
const HostUrl = host.service;
const Requ = new Request();
var app = getApp();

Page({

  /**
   * 页面的初始数据
   */
  data: {
    navH: 0, //页面高度
    sptab_choose: 1, //商品标签切换
    winheight: 0,   //商品列表高度
    tabindex: 2,   //商品切换id
    //商品分组列表
    GroupList:[
      {
        img:'',
        name:'特色菜系'
      },
      {
        img:'',
        name:'全球美食'
      },
      {
        img:'',
        name:'特色菜系'
      },
      {
        img:'',
        name:'全球美食'
      }
    ],
	isShowShopCar:false
  },
  // 返回上一层
  goHome: function (e) {
    wx.navigateBack({
      delta: 1,
    })
  },
  // 拨打电话
  PayPhone:function(e){
    wx.makePhoneCall({
      phoneNumber: e.currentTarget.dataset.phone
    })
    e
  },
  //商品标签切换
  Choosetab: function (e) {
    this.setData({
      sptab_choose: e.currentTarget.dataset.id
    })
  },
  // 商品类别/分组切换
  Choose_splist: function(event) {
    this.groupid =  event.currentTarget.dataset.groupid; // 点击分组序号
    //赋值给tabindex
    this.setData({
      tabindex: event.currentTarget.dataset.id,
      GoodsList: this.goods[event.currentTarget.dataset.groupid]['goods'],  // 商品列表
    });
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.data.MS_id = options.MS_id; // 店铺id
	/* this.data.MS_id = 10040 */
    this.setData({
      navH: app.globalData.navHeight,
    });
    let windowHeight = wx.getSystemInfoSync().windowHeight // 屏幕的高度
    let windowWidth = wx.getSystemInfoSync().windowWidth // 屏幕的宽度
    this.setData({
      winheight: windowHeight * 750 / windowWidth - 800
    });
    new Request('get_shopgoods.cls.php').request(
      () => {
        return {
          shop_id: this.data.MS_id,
          openid: app.globalData.openid,
        }
      },
      (res) => {
        this.response = res.data;  // 响应参数
        let response = res.data;  // 响应参数
        let shopInfo = response.shopinfo;
        let shopDeatil = response.shop;
        this.goods = response.goods;  // 分组名、商品
        let group = Array(); // 定义商品分组变量
        // 商品列表
        if(Func.is_var(res.data, 'goods')){
          this.goods.map((e,n)=>{
            e.goods.map((s,m)=>{
              s.image = HostUrl.HostName + s.image; // 商品图片
              s.price = parseFloat(s['price']).toFixed(2); // 商品价格保留两位小数，1111.1111
            });
            // 取出商品分组
            group.push({img: '', name: e.group});
          });
        }else{
          Requ.showToast('该店铺商品还未上新');
          this.goods = [{goods:1}];
          this.goods[0]['goods'] = new Array();
        }
		console.log(this.goods)
		console.log(app.globalData.shopCart)
		let length = app.globalData.shopCart.length
		let flag = 1
		for(let i =0;i<length;i++){
		  if(app.globalData.shopCart[i].shopId == this.data.MS_id){
			  console.log(app.globalData.shopCart[i].shopId)
			  console.log(this.data.MS_id)
			  this.data.shopCar = []
			  this.data.shopCar[0] = app.globalData.shopCart[i]
			  this.setData({
				  shopCar:this.data.shopCar
			  })
			  console.log(this.data.shopCar)
			  flag = 0
			  let len = app.globalData.shopCart[i].data.length
			  for(let j=0;j<len;j++){
				  let goodsLength = this.goods.length
				  for(let m=0;m<goodsLength;m++){
					  let groupLength = this.goods[m].goods.length
					  for(let n = 0;n<groupLength;n++){
						  if(this.goods[m].goods[n].id==app.globalData.shopCart[i].data[j].id){
							  this.goods[m].goods[n].num = app.globalData.shopCart[i].data[j].num
							  break
						  }
					  }
				  }
			  }
			  break
		  }
		}
		if(flag){
			this.data.shopCar = []
			this.data.shopCar[0] = {}
			this.data.shopCar[0].addprice = 0
			this.data.shopCar[0].addprice = this.data.shopCar[0].addprice.toFixed(2)
			this.data.shopCar[0].optionalnum = 0
			this.data.shopCar[0].data = []
			this.setData({
				shopCar:this.data.shopCar
			})
		}
        this.setData({
          GroupList: group,
          GoodsList: this.goods[0]['goods'],
          ShopLogo: HostUrl.HostName + shopDeatil.logo,
          shopInfo:shopInfo,
          shop: shopDeatil,
        });
        this.groupid = 0; //  起始分组序号
      });
  },
  // 加入商品
  GoodsAdd: function(event){
    this.response['goods'][this.groupid]['goods'][event.currentTarget.dataset.goodsid].num++;
    let goodsInfo = this.response['goods'][this.groupid]['goods'][event.currentTarget.dataset.goodsid];
    // 合并重复 并增加数量
    const merge = (s1, s2) => {
      const map = new Map();
      for(let i = 0; i < s1.length; ++i) {
        map.set(s1[i].id, s1[i]);
      }
      for(let i = 0; i < s2.length; ++i) {
        if(map.has(s2[i].id)) {
          // console.log(s2[i]);
          map.get(s2[i].id).num = map.get(s2[i].id).num + s2[i].num;
          map.get(s2[i].id).groupprice = parseFloat(map.get(s2[i].id).num *  map.get(s2[i].id).addprice).toFixed(2);
        }
        else map.set(s2[i].id, s2[i]);
      }
      return Array.from(map.values());
    }
    // 追加商品数据
    let AddGoodsInfo = new Array({
      optional: 1,
      name: goodsInfo['name'],
      addprice: goodsInfo['price'],
      num: 1, // 每操作一次加一
      image: goodsInfo['image'],
      id: goodsInfo['id'],
      specifcar: goodsInfo['specifcar'],
      groupprice: parseFloat(goodsInfo['price']).toFixed(2),
    });
	console.log(this.data.shopCar[0])
    this.data.shopCar[0]['data'] = merge(this.data.shopCar[0]['data'], AddGoodsInfo); // 商品购物车
    let addprice = 0;
    let optionalnum = 0;
    // 总计
    this.data.shopCar[0]['data'].map((e)=>{
      addprice = parseFloat(addprice) +  parseFloat(e.groupprice);
      optionalnum = optionalnum + parseFloat(e.num);
    });
    this.data.shopCar[0]['addprice']    = parseFloat(addprice).toFixed(2);     // 商品总和
    this.data.shopCar[0]['optionalnum'] = optionalnum;  // 商品数量

    this.setData({
      GoodsList: this.goods[this.groupid]['goods'],
      shopCar: this.data.shopCar,
    });
    // console.log(shopCar[0]);
    wx.request({
      url: HostUrl.SZXURL + HostUrl.AddCart,
      method: 'POST',
      data: {
        id: this.response['goods'][this.groupid]['goods'][event.currentTarget.dataset.goodsid].id,
        num: this.response['goods'][this.groupid]['goods'][event.currentTarget.dataset.goodsid].num,
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded',
        'openid': app.globalData.openid,
      },
      success: (setData) => {
        if(setData.data.code == 1){
          // Requ.showToast('附件暂无提货点');
          return;
        }
      }
    });
  },
  // 减入商品
  GoodsDel: function(event){
    if(this.response['goods'][this.groupid]['goods'][event.currentTarget.dataset.goodsid].num <= 0){
      /* Requ.showToast('Nope'); */
      return;
    }
    this.response['goods'][this.groupid]['goods'][event.currentTarget.dataset.goodsid].num--; // 自减商品
    let goodsInfo = this.response['goods'][this.groupid]['goods'][event.currentTarget.dataset.goodsid];
	console.log(goodsInfo)
    this.data.shopCar[0]['data'].map((e,n)=>{
      if(e.id == goodsInfo['id']){
        this.data.shopCar[0]['data'][n].num--;
		this.data.shopCar[0]['data'][n].groupprice = (this.data.shopCar[0]['data'][n].num * this.data.shopCar[0]['data'][n].addprice).toFixed(2)
        this.data.shopCar[0]['optionalnum']--;
        this.data.shopCar[0]['addprice'] = parseFloat(this.data.shopCar[0]['addprice'] - this.data.shopCar[0]['data'][n].addprice).toFixed(2);
        if(this.data.shopCar[0]['data'][n].num == 0){
          this.data.shopCar[0]['data'].splice(n, 1);  // 移除商品
        }
      }
    });
    console.log(this.data.shopCar[0]);
    this.setData({
      GoodsList: this.goods[this.groupid]['goods'],
      shopCar: this.data.shopCar,
    });
    wx.request({
      url: HostUrl.SZXURL + HostUrl.UpCart,
      method: 'POST',
      data: {
        id: this.response['goods'][this.groupid]['goods'][event.currentTarget.dataset.goodsid].id,
        num: this.response['goods'][this.groupid]['goods'][event.currentTarget.dataset.goodsid].num,
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded',
        'openid': app.globalData.openid,
      },
      success: (setData) => {
        if(setData.data.code == 1){
          // Requ.showToast('附件暂无提货点');
          return;
        }

      }
    });
  },
  //将已选商品加入购物车
  AddToShopCart:function(){
	  console.log(this.data.shopCar)
	  /* wx.navigateTo({
		  url:'/pages/shopcar/shopcar'
	  }) */
	  let len = this.data.shopCar[0].data.length
	  for(let i =0;i<len;i++){
		  this.data.shopCar[0].data[i].active = true
	  }
	  this.data.shopCar[0].shopId = this.data.MS_id
	  this.data.shopCar[0].shopName = this.data.shop.name
	  let length = app.globalData.shopCart.length
	  let flag = 1
	  for(let i =0;i<length;i++){
		  if(app.globalData.shopCart[i].shopId == this.data.shopCar[0].shopId){
			  app.globalData.shopCart[i] = this.data.shopCar[0]
			  flag = 0
			  break
		  }
	  }
	  if(flag){
		  app.globalData.shopCart.push(this.data.shopCar[0])
	  }
	  wx.showToast({
	      title: '添加成功',
	      icon: 'none',
	      duration: 2000
	  })
	  /* wx.switchTab({
		  url:"/pages/self_take/self_take"
	  }) */
  },
  // 跳转购物车页面
  GoToShopCar: function(event){
    console.log(shopCar)
    this.setData({
		isShowShopCar:!this.data.isShowShopCar
	})
  },
  // 预览图片
  PreImage: function (e) {
    Func.PreImage(e.currentTarget.dataset.image, e.currentTarget.dataset.image);
  },
  // 创建订单
  GoToPay: function(){
	  console.log(shopCar)
    if(this.data.shopCar[0]['data'] == 0){
      Requ.showToast('请选择商品', 'error');
      return;
    }
    if(this.data.shop.state == 1){
      Requ.showToast('店铺已打样', 'error');
      return;
    }
    Func.CreateOrder(JSON.stringify(this.data.shopCar), this.MS_id);
    return;
    new Request('create_order.cls.php').request(
      () => {
        return {
          goods: JSON.stringify(this.data.shopCar),
          shopid: this.MS_id,
          openid: app.globalData.openid,
        }
      },
      (res) => {
        wx.redirectTo({
          url: '/pages/self_take/self_take?orderid=' + res.data.orderid
        });
      });
  },
  /**
   * 生命周期函数--监听页面卸载
   */
  /* onUnload: function () {    
    shopCar = new Array({data:[], optionalnum:0, type:1, addprice:'0.00'});  // 购物车
    this.goods.map((e,n)=>{
      e.goods.map((s,m)=>{
        s.num = 0;
      });
    });
    this.setData({
      shopCar:shopCar,
      GoodsList: this.goods[0]['goods'],
    });
  }, */
  /**
   * 生命周期函数--监听页面隐藏
   */
  /* onHide: function () {
    shopCar = new Array({data:[], optionalnum:0, type:1, addprice:'0.00'});  // 购物车
    this.goods.map((e,n)=>{
      e.goods.map((s,m)=>{
        s.num = 0;
      });
    });
    this.setData({
      shopCar:shopCar,
      GoodsList: this.goods[0]['goods'],
    });
  }, */
})